package net.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/downloadfile")
public class DownloadFileController {

	/**
	 * Size of a byte buffer to read/write file
	 */
	private static final int BUFFER_SIZE = 4096;

	@Autowired
	ServletContext servletContext;

	// Process the form.
	@RequestMapping(method = RequestMethod.GET)
	public void showRegistration(HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws IOException {
//		System.out.println("DownloadFileController.showRegistration GET");

		// get absolute path of the application
		String appPath = servletContext.getRealPath("");
//		System.out.println("appPath = " + appPath);

		// Path of the file to be downloaded, relative to application's
		// directory
		String filePath = (String) session.getAttribute("uploadFile");
		if (filePath != null && !filePath.equals("")) {
			// construct the complete absolute path of the file
			String fullPath = appPath + "\\" + filePath;
			File downloadFile = new File(fullPath);
			FileInputStream inputStream = new FileInputStream(downloadFile);

			// get MIME type of the file
			String mimeType = servletContext.getMimeType(fullPath);
			if (mimeType == null) {
				// set to binary type if MIME mapping not found
				mimeType = "application/octet-stream";
//				System.out.println("MIME type: " + mimeType);
			}
			// set content attributes for the response
			response.setContentType(mimeType);
			response.setContentLength((int) downloadFile.length());

			// set headers for the response
			String headerKey = "Content-Disposition";
			String headerValue = String.format("attachment; filename=\"%s\"",
					downloadFile.getName());
			response.setHeader(headerKey, headerValue);

			// get output stream of the response
			OutputStream outStream = response.getOutputStream();
			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;
			// write bytes read from the input stream into the output stream
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, bytesRead);
			}
			inputStream.close();
			outStream.close();
		}
	}
}
